package com.yxhl.zoume.core.user.ui.fragment.mywallet;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.jakewharton.rxbinding.view.RxView;
import com.yxhl.zoume.R;
import com.yxhl.zoume.common.ui.fragment.BaseFragment;
import com.yxhl.zoume.core.func.pay.presenter.AliPayPresenter;
import com.yxhl.zoume.core.func.pay.presenter.WeChatPayPresenter;
import com.yxhl.zoume.core.func.pay.view.AliPayView;
import com.yxhl.zoume.core.func.pay.view.WeChatPayView;
import com.yxhl.zoume.core.user.ui.activity.MyWalletActivity;
import com.yxhl.zoume.core.user.ui.info.MyWalletEntry;
import com.yxhl.zoume.core.user.ui.info.WeChatResultEvent;
import com.yxhl.zoume.di.component.pay.DaggerOrderPayComponent;
import com.yxhl.zoume.di.component.pay.OrderPayComponent;
import com.yxhl.zoume.di.module.ActivityModule;
import com.yxhl.zoume.utils.LOG;
import com.yxhl.zoume.utils.PromptUtils;
import com.yxhl.zoume.utils.WeChatPayEntryUtils;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import rx.functions.Action1;

/**
 * 项目名称：Ferrari
 * Created by menggod on 16/11/3 .
 */

public class WalletRechargeFragment extends BaseFragment implements AliPayView, WeChatPayView {
    private static final String TAG = "WalletRechargeFragment";
    //各种金额
    @BindView(R.id.tv_recharge_50)
    TextView mTvRecharge50;
    @BindView(R.id.tv_recharge_100)
    TextView mTvRecharge100;
    @BindView(R.id.tv_recharge_200)
    TextView mTvRecharge200;
    @BindView(R.id.tv_recharge_300)
    TextView mTvRecharge300;
    @BindView(R.id.tv_recharge_500)
    TextView mTvRecharge500;
    @BindView(R.id.et_recharge_other)
    EditText mEtRechargeOther;
    //微信
    @BindView(R.id.iv_recharge_wechat)
    ImageView mIvRechargeWechat;
    @BindView(R.id.ll_recharge_wechat)
    LinearLayout mLlRechargeWechat;
    //支付宝
    @BindView(R.id.iv_recharge_alipay)
    ImageView mIvRechargeAlipay;
    @BindView(R.id.ll_recharge_alipay)
    LinearLayout mLlRechargeAlipay;
    @BindView(R.id.btn_recharge_commit)
    Button mBtnRechargeCommit;

    private View moneyView;

    private View payWayView;

    private int money;

    MaterialDialog dialogForWaitingDetail = null;
    /**
     * 支付宝充值
     */
    @Inject
    public AliPayPresenter aliPayPresenter;
    /**
     * 微信充值
     */
    @Inject
    public WeChatPayPresenter weChatPayPresenter;
    private OrderPayComponent mComponent;
    private MyWalletActivity mWalletActivity;

    public static WalletRechargeFragment newInstance() {
        WalletRechargeFragment fragment = new WalletRechargeFragment();
        return fragment;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onRxBusEvent();
        onRechargeControl();
        initEditTextControl();
        initPaywayControl();
        initInputKey(view);
        mWalletActivity = (MyWalletActivity) getActivity();
        aliPayPresenter.attachView(this);
        weChatPayPresenter.attachView(this);
    }

    private void initInputKey(View view) {
        mEtRechargeOther.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    InputMethodManager imm = (InputMethodManager) v
                            .getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(
                                v.getApplicationWindowToken(), 0);
                    }
                    return true;
                }
                return false;
            }
        });
//点击其他部位隐藏软键盘
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                InputMethodManager manager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (getActivity().getCurrentFocus() != null && getActivity().getCurrentFocus().getWindowToken() != null) {
                        manager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
                return false;
            }
        });

    }


    private void onRxBusEvent() {
        //微信充值结果判断
        getSubscription().add(toSubscription(WeChatResultEvent.class,
                new Action1<WeChatResultEvent>() {
                    @Override
                    public void call(WeChatResultEvent weChatResultEvent) {
                        if (weChatResultEvent != null) {
                            boolean isSuccess = weChatResultEvent.isSuccess();
                            if (isSuccess) {
                                mWalletActivity.showRechargeResultFragment(MyWalletEntry.RECHARGE_SUCCESS, money);
                            } else {
                                mWalletActivity.showRechargeResultFragment(MyWalletEntry.RECHARGE_FAILURE, money);
                            }

                        }
                    }
                }));
    }

    @Override
    public void onPause() {
        super.onPause();
        aliPayPresenter.onPause();
        weChatPayPresenter.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        aliPayPresenter.onResume();
        weChatPayPresenter.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        aliPayPresenter.onDestroy();
        weChatPayPresenter.onDestroy();
    }

    private void initPaywayControl() {
        payWayView = mIvRechargeWechat;
        payWayView.setSelected(true);
    }

    private void initEditTextControl() {
        mEtRechargeOther.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setOtherRecharge();
            }

            private void setOtherRecharge() {
                String etStringMoney = mEtRechargeOther.getText().toString().trim();
                if (etStringMoney.length() > 0) {
                    int etMoney = Integer.parseInt((String) etStringMoney);
                    if (etMoney > 0) {
                        setMoneySelect(mEtRechargeOther, etMoney);
                    }
                } else {
                    mEtRechargeOther.setSelected(false);
                    mBtnRechargeCommit.setEnabled(false);
                    mBtnRechargeCommit.setText("账户充值");
                }
            }
        });
    }

    private void onRechargeControl() {
        RxView.clicks(mBtnRechargeCommit).throttleFirst(3, TimeUnit.SECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        rechargeCommit();
                    }
                });
    }

    /**
     * 提交
     * mIvRechargeAlipay mIvRechargeWechat
     */
    private void rechargeCommit() {
        showWaitingDialog(true);
        WeChatPayEntryUtils.getInstance(mActivity).saveWechatRechargeEntry(true);
        if (payWayView == mIvRechargeAlipay) {
            aliPayPresenter.getAliRechargeSignedStr(mActivity, String.valueOf(money));
        }
        if (payWayView == mIvRechargeWechat) {
            weChatPayPresenter.getWeChatRechargeSignedStr(mActivity, String.valueOf(money));
        }
    }


    @Override
    protected void initializeInjector() {
        mComponent = DaggerOrderPayComponent
                .builder()
                .activityModule(new ActivityModule(mActivity))
                .appComponent(getAppComponent())
                .build();
        mComponent.inject(this);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_recharge_ing;
    }

    @Override
    protected void setupToolBar() {
        ((MyWalletActivity) mActivity).setToolbarTitle("账户充值");
    }


    @OnClick({R.id.tv_recharge_50, R.id.tv_recharge_100, R.id.tv_recharge_200, R.id.tv_recharge_300, R.id.tv_recharge_500, R.id.et_recharge_other})
    public void onMoneyClick(View view) {
        LOG.e(TAG, view.getId() + "");
        switch (view.getId()) {
            case R.id.tv_recharge_50:
                processEditTextFocuse();
                setMoneySelect(mTvRecharge50, 50);
                break;
            case R.id.tv_recharge_100:
                processEditTextFocuse();
                setMoneySelect(mTvRecharge100, 100);
                break;
            case R.id.tv_recharge_200:
                processEditTextFocuse();
                setMoneySelect(mTvRecharge200, 200);
                break;
            case R.id.tv_recharge_300:
                processEditTextFocuse();
                setMoneySelect(mTvRecharge300, 300);
                break;
            case R.id.tv_recharge_500:
                processEditTextFocuse();
                setMoneySelect(mTvRecharge500, 500);
                break;
            case R.id.et_recharge_other:
                String moneyShow = mEtRechargeOther.getText().toString();
                if (moneyShow.length() > 0) {
                    int moneyInt = Integer.parseInt(moneyShow);
                    if (moneyInt > 0) {
                        setMoneySelect(mEtRechargeOther, moneyInt);
                    }
                } else {

                }
                break;
        }
    }

    @OnClick({R.id.ll_recharge_wechat, R.id.ll_recharge_alipay})
    public void onPayWayClick(View view) {
        switch (view.getId()) {
            case R.id.ll_recharge_wechat:
                setPayWaySelect(mIvRechargeWechat);
                break;
            case R.id.ll_recharge_alipay:
                setPayWaySelect(mIvRechargeAlipay);
                break;
        }
    }

    /**
     * 钱选择
     *
     * @param view
     * @param money
     */
    public void setMoneySelect(View view, int money) {
        if (null != moneyView) {
            moneyView.setSelected(false);
            moneyView = view;
        } else {
            moneyView = view;
        }
        moneyView.setSelected(true);
        this.money = money;
        mBtnRechargeCommit.setEnabled(true);
        mBtnRechargeCommit.setText("确认充值" + money + "元");
    }

    public void processEditTextFocuse() {
        if(mEtRechargeOther.getText().toString().trim().length()>0) {
            mEtRechargeOther.setText("");
            mEtRechargeOther.clearFocus();
            getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            boolean isOpen = imm.isActive();
            if (isOpen) {
                imm.hideSoftInputFromWindow(mEtRechargeOther.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 充值方式
     *
     * @param view
     */
    public void setPayWaySelect(View view) {
        if (null != payWayView) {
            payWayView.setSelected(false);
            payWayView = view;
        } else {
            payWayView = view;
        }
        payWayView.setSelected(true);
    }

    /**
     * 支付回调
     */

    @Override
    public void renderAliPaySucceed() {
        showWaitingDialog(false);
        mWalletActivity.showRechargeResultFragment(MyWalletEntry.RECHARGE_SUCCESS, money);
    }

    @Override
    public void renderAliPayFailure(String resultStatus) {
        showWaitingDialog(false);
        PromptUtils.showShort(mActivity, resultStatus);
        mWalletActivity.showRechargeResultFragment(MyWalletEntry.RECHARGE_FAILURE, money);
    }

    @Override
    public void renderAliPaySignedError() {
        showWaitingDialog(false);
        PromptUtils.showShort(mActivity, "网络错误");
        mWalletActivity.showRechargeResultFragment(MyWalletEntry.RECHARGE_FAILURE, money);
    }

    @Override
    public void dismissWaitingDialog() {
        showWaitingDialog(false);
    }

    @Override
    public void showErrorMessage(String errorMessage) {
        PromptUtils.showShort(mActivity, errorMessage);
        showWaitingDialog(false);
    }

    @Override
    public void showWechatUninstalledDialog() {

    }

    public void showWaitingDialog(boolean isWaiting) {
        if (isWaiting) {
            dialogForWaitingDetail = new MaterialDialog.Builder(mComponent.context())
                    .content(R.string.dialog_waiting_processing)
                    .progress(true, 0)
                    .canceledOnTouchOutside(false)
                    .show();
        } else {
            if (null != dialogForWaitingDetail) {
                dialogForWaitingDetail.dismiss();
            }
        }

    }

}
